import os
from tkinter import ttk
import tkinter as tk

class WinSearch:
    def __init__(self, search_path, search_name, win_search_path, win_tree):
        self.search_path = search_path
        # 搜索框的内容
        self.search_name = search_name
        self.win_search_path = win_search_path
        self.tree = win_tree

        # # 滚动条
        # sy = tk.Scrollbar(self.center_frame)
        # sy.pack(side=tk.RIGHT, fill=tk.Y)
        # sy.config(command=self.tree.yview)
        # self.tree.config(yscrollcommand=sy.set)

        # 绑定事件
        self.tree.bind("<<TreeviewSelect>>", self.func)
        self.tree.pack(expand=True, fill=tk.BOTH)
        self.ev = tk.Variable()


    # 搜索关键词目录
    def search_keyword_dirs(self, root1, dirs):
        for _dir in dirs:
            if -1 != _dir.find(self.search_name) and _dir[0] != '$':
                AllDir = os.path.join(root1, _dir)
                self.tree.insert("", "end", text=AllDir, values=(AllDir,))

    # 搜索关键词文件
    def search_keyword_files(self, root, files):
        for file in files:
            if self.search_name in file:
                AllFile = os.path.join(root, file)

                self.tree.insert("", "end", text=AllFile, values=(AllFile,))

    # 搜索
    def search(self):
        curdisks = self.search_path
        # root 当前正在遍历的这个文件夹的本身的地址
        # dirs 是一个 list ，内容是该文件夹中所有的目录的名字
        # files 同样是 list , 内容是该文件夹中所有的文件
        for root, dirs, files in os.walk(curdisks):
            self.search_keyword_dirs(root, dirs)
            self.search_keyword_files(root,  files)



    def func(self, event):
        # widget触发事件的构建
        self.v = event.widget.selection()
        for sv in self.v:
            file = self.tree.item(sv)["text"]
            self.ev.set(file)
            apath = self.tree.item(sv)["values"][0]

            self.win_search_path.clear()
            self.win_search_path.append(apath)
            print(self.win_search_path)
            print(apath)

